//! 正则的常见用法
//! 
use std::{collections::HashMap, fs};

use regex::Regex;

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize)]
struct Config {
    title: String,
    attr: Vec<String>,
    table: Vec<String>
}

#[derive(Serialize)]
struct ParseItem {
    x_plus_y: f32,
    name: String,
    value:Option<String>
}

/// 读取单据特征描述文档
fn read_document_feautre() -> HashMap<String, Option<ParseItem>> {
    let doc = fs::read_to_string("./documentFueature.json").unwrap();
    // 解析 JSON
    let confif = serde_json::from_str::<Config>(&doc).unwrap();

    let mut cache = HashMap::<String, Option<ParseItem>>::new();
    cache.insert(confif.title.clone(), None);
    for a in confif.attr {
        cache.insert(a.clone(), None);
    }
    for t in confif.table {
        cache.insert(t.clone(), None);
    }
    return cache;
}

fn hello() {
    print!("123")
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test1() {
        // 输入数据
    let input = r#"
        [2025/02/21 14:44:26] ppocr INFO: [[[445.0, 356.0], [971.0, 364.0], [970.0, 395.0], [444.0, 387.0]], ('江苏康为世纪生物科技股份有限公司销售出库单', 0.9912107586860657)]
        [2025/02/21 14:44:26] ppocr INFO: [[[183.0, 385.0], [270.0, 389.0], [269.0, 418.0], [182.0, 414.0]], ('出库日期：', 0.9883357882499695)]
        [2025/02/21 14:44:26] ppocr INFO: [[[292.0, 387.0], [407.0, 391.0], [406.0, 417.0], [291.0, 414.0]], ('2023-10-18', 0.9921366572380066)]
        [2025/02/21 14:44:26] ppocr INFO: [[[566.0, 393.0], [794.0, 397.0], [794.0, 422.0], [566.0, 419.0]], ('出库单号：XSCKD162692', 0.9870765209197998)]
        [2025/02/21 14:44:26] ppocr INFO: [[[897.0, 400.0], [986.0, 400.0], [986.0, 427.0], [897.0, 427.0]], ('客服电话：', 0.9946282505989075)]
        [2025/02/21 14:44:26] ppocr INFO: [[[1010.0, 400.0], [1144.0, 400.0], [1144.0, 427.0], [1010.0, 427.0]], ('4006-222-360', 0.9953286051750183)]
        [2025/02/21 14:44:26] ppocr INFO: [[[180.0, 415.0], [272.0, 419.0], [271.0, 447.0], [179.0, 443.0]], ('客户名称：', 0.9829074740409851)]
        [2025/02/21 14:44:26] ppocr INFO: [[[292.0, 417.0], [560.0, 424.0], [559.0, 450.0], [291.0, 444.0]], ('浙江博圣生物技术股份有限公司', 0.995539665222168)]
        [2025/02/21 14:44:26] ppocr INFO: [[[897.0, 428.0], [995.0, 428.0], [995.0, 455.0], [897.0, 455.0]], ('联系人：', 0.97874516248703)]
        [2025/02/21 14:44:26] ppocr INFO: [[[1010.0, 430.0], [1055.0, 430.0], [1055.0, 453.0], [1010.0, 453.0]], ('朱华', 0.9885464906692505)]
        [2025/02/21 14:44:26] ppocr INFO: [[[1116.0, 433.0], [1259.0, 433.0], [1259.0, 455.0], [1116.0, 455.0]], ('0571-89905544', 0.9956492781639099)]
        [2025/02/21 14:44:26] ppocr INFO: [[[181.0, 444.0], [270.0, 444.0], [270.0, 470.0], [181.0, 470.0]], ('客户地址：', 0.9898136854171753)]
        [2025/02/21 14:44:26] ppocr INFO: [[[292.0, 445.0], [744.0, 450.0], [744.0, 477.0], [291.0, 472.0]], ('浙江省杭州市西湖区三墩镇金蓬街366号2幢201室冷库', 0.9766709804534912)]
        [2025/02/21 14:44:26] ppocr INFO: [[[179.0, 474.0], [259.0, 474.0], [259.0, 496.0], [179.0, 496.0]], ('发票抬头', 0.8592329025268555)]
        [2025/02/21 14:44:26] ppocr INFO: [[[290.0, 472.0], [558.0, 475.0], [558.0, 502.0], [290.0, 499.0]], ('浙江博圣生物技术股份有限公司', 0.9950094223022461)]
        [2025/02/21 14:44:26] ppocr INFO: [[[896.0, 480.0], [991.0, 483.0], [990.0, 512.0], [895.0, 508.0]], ('业务员：', 0.9670349359512329)]
        [2025/02/21 14:44:26] ppocr INFO: [[[1012.0, 485.0], [1072.0, 485.0], [1072.0, 508.0], [1012.0, 508.0]], ('赖明才', 0.9600557684898376)]
        [2025/02/21 14:44:26] ppocr INFO: [[[167.0, 519.0], [239.0, 519.0], [239.0, 543.0], [167.0, 543.0]], ('物料编码', 0.9869253039360046)]
        [2025/02/21 14:44:26] ppocr INFO: [[[268.0, 522.0], [342.0, 522.0], [342.0, 546.0], [268.0, 546.0]], ('物料名称', 0.9883162975311279)]
        "#;
        let re = Regex::new(r"\[\[\[(\d+\.\d+,\s*\d+\.\d+)\],\s*\[(\d+\.\d+,\s*\d+\.\d+)\],\s*\[(\d+\.\d+,\s*\d+\.\d+)\],\s*\[(\d+\.\d+,\s*\d+\.\d+)\]\],\s*\('([^']+)',\s*([0-1]\.\d+)\)\]").unwrap();
        let mut cache = read_document_feautre();
        
        for line in input.lines()  {
            for cap in re.captures_iter(line) {
                // 提取第一个坐标 [x1, y1]
                let first_coord_str = &cap[1];
                println!("{}", first_coord_str);
                let first_coords: Vec<f32> = first_coord_str
                    .split(',')
                    .map(|s| s.trim().parse::<f32>().unwrap())
                    .collect();
                let name = &cap[5];
                if cache.contains_key(name) {
                    if name.contains(":") {
                        if let Some((_, value)) = name.split_once('：') {
                            cache.entry(name.to_string())
                                .and_modify(|entry| {
                                    *entry = Some(ParseItem {x_plus_y: first_coords[0]+first_coords[1], name: name.to_string(), value: Some(value.to_string())}); // 赋值新值
                                });
                            continue;
                        }
                    }
                    cache.entry(name.to_string())
                        .and_modify(|entry| {
                            *entry = Some(ParseItem {x_plus_y: first_coords[0]+first_coords[1], name: name.to_string(), value: None}); // 赋值新值
                        });
                } else {
                    let total = first_coords[0]+first_coords[1];
                    let closest_entry = cache
                    .iter_mut()
                    .filter_map(|(key, value)| value.as_mut().map(|item| (key, item))) // 过滤 None 并获取可变引用
                    .min_by(|a, b| (total - a.1.x_plus_y).partial_cmp(&(total - b.1.x_plus_y)).unwrap());

                    if let Some((_, item)) = closest_entry {
                        item.value = Some(name.to_string());
                    }
                }
                
                
            }
        }

        // 转换为 JSON 字符串
        let json_str = serde_json::to_string_pretty(&cache).unwrap();

        // 打印 JSON
        println!("{}", json_str);
    }

    #[test]
    fn test_read_file() {
        read_document_feautre();
    }
}